package com.ruoyi.system.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.core.page.PageDomain;
import com.ruoyi.common.core.page.TableSupport;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.framework.web.domain.server.Sys;
import com.ruoyi.system.constant.Constants;
import com.ruoyi.system.domain.IbrainTask;
import com.ruoyi.system.domain.ScrTotalanduser;
import com.ruoyi.system.domain.UserInfo;
import com.ruoyi.system.service.IUserInfoService;
import com.ruoyi.system.utils.PageByList;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.system.domain.ScrTotal;
import com.ruoyi.system.service.IScrTotalService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 【请填写功能名称】Controller
 *
 * @author ruoyi
 * @date 2024-01-23
 */
@RestController
@RequestMapping("/system/total")
public class ScrTotalController extends BaseController
{
    @Autowired
    private IScrTotalService scrTotalService;

    @Autowired
    private IUserInfoService userInfoService;

    /**
     * 查询【请填写功能名称】列表
     */

/*    @GetMapping("/list")
    public TableDataInfo list(ScrTotal scrTotal, @CookieValue(value = "username", defaultValue = "") String username)
//    public TableDataInfo list(ScrTotal scrTotal)
    {
//        String username = "admin";
        startPage();
//        List<ScrTotal> list = scrTotalService.selectScrTotalList(scrTotal);

        System.out.println(username);

        List<ScrTotal> list = scrTotalService.selectScrTotalListByUsername(username);

        for(ScrTotal scrTotal1 : list){
            Long id = scrTotal1.getUserInfoId();
            UserInfo userInfo = userInfoService.selectUserInfoById(id);
            scrTotal1.setName(userInfo.getName());
        }
        return getDataTable(list);
    }*/



    @GetMapping("/list")
    public TableDataInfo list(ScrTotal scrTotal)
    {
        String username = SecurityUtils.getUsername();
        String name = scrTotal.getName();
        scrTotal.setName("");
        HashMap<Long,Integer> idmap = new HashMap<>();
        idmap = scrTotalService.selectScrTotalListbyuser(scrTotal,username);
        List<ScrTotal> scrTotalList = scrTotalService.selectScrTotalList(scrTotal);
        List<ScrTotal> retList = new ArrayList<>();
        for(ScrTotal scrTotal1 : scrTotalList){
            if(idmap.containsKey(scrTotal1.getScrId())){
                retList.add(scrTotal1);
            }
        }
        scrTotalList.clear();
        for(ScrTotal scrTotal1:retList){
            scrTotalList.add(scrTotal1);
        }

        List<ScrTotal> list1 = new ArrayList<>();
        for(ScrTotal scrTotal1 : scrTotalList){
            Long id = scrTotal1.getUserInfoId();
            UserInfo userInfo = userInfoService.selectUserInfoById(id);
            scrTotal1.setName(userInfo.getName());
            if(name == null || scrTotal1.getName().contains(name)){
                list1.add(scrTotal1);
            }
        }
        scrTotalList.clear();
        for(ScrTotal scrTotal1:list1){
            scrTotalList.add(scrTotal1);
        }





        PageDomain pageDomain = TableSupport.buildPageRequest();
        Integer pageNum = pageDomain.getPageNum();
        Integer pageSize = pageDomain.getPageSize();
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(0);
        rspData.setRows(PageByList.startPage(scrTotalList, pageNum, pageSize));
        rspData.setTotal(new PageInfo(scrTotalList).getTotal());
        return rspData;

    }





    /**
     * 导出【请填写功能名称】列表
     */

    @PostMapping("/export")
    public void export(HttpServletResponse response, ScrTotalanduser scrTotalanduser)
    {
        List<ScrTotalanduser> list = scrTotalService.selectScrTotalanduserList(scrTotalanduser);
        ExcelUtil<ScrTotalanduser> util = new ExcelUtil<ScrTotalanduser>(ScrTotalanduser.class);
        util.exportExcel(response, list, "电子量表数据");
    }


    @PostMapping("/export1")
    public void export1(HttpServletResponse response, ScrTotalanduser scrTotalanduser)
    {
        ScrTotal scrTotal = new ScrTotal();
        List<ScrTotal> list = scrTotalService.selectScrTotalList(scrTotal);
        ExcelUtil<ScrTotal> util = new ExcelUtil<ScrTotal>(ScrTotal.class);
        util.exportExcel(response, list, "电子量表数据");
    }


    /**
     * 获取【请填写功能名称】详细信息
     */

    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(scrTotalService.selectScrTotalById(id));
    }


    @GetMapping(value = "/getuser{id}")
    public AjaxResult getuserInfo(@PathVariable("id") Long id) throws IOException {
        ScrTotal scrTotal = scrTotalService.selectScrTotalById(id);
        if(scrTotal.getUserInfoId()==-1){
            UserInfo userInfo = new UserInfo();
            userInfo.setName("未命名");
            userInfoService.insertUserInfo(userInfo);
            scrTotal.setUserInfoId(userInfo.getId());
            scrTotalService.updateScrTotal(scrTotal);
            return success(userInfo);
        }
        else {
            return success(userInfoService.selectUserInfoById(scrTotal.getUserInfoId()));
        }
    }

    @GetMapping(value = "/getscrid{id}")
    public AjaxResult getscrid(@PathVariable("id") Long id)
    {
        ScrTotal scrTotal = scrTotalService.selectScrTotalById(id);
        String url = "http://images.headdb.cn/"+"base_"+scrTotal.getScrId()+"_54402.png";//TODO:nginx要改
        //List<String>url = null;
        //url.add("D:\\nginx\\nginx-1.24.0\\nginx-1.24.0\\html\\"+"base_"+scrTotal.getScrId()+"_54257.png");
        //url.add("D:\\nginx\\nginx-1.24.0\\nginx-1.24.0\\html\\"+"base_"+scrTotal.getScrId()+"_54258.png");
        //url.add("D:\\nginx\\nginx-1.24.0\\nginx-1.24.0\\html\\"+"base_"+scrTotal.getScrId()+"_54259.png");
        return success(url);
    }


    /**
     * 新增【请填写功能名称】
     */

    @PostMapping
    public AjaxResult add(@RequestBody ScrTotal scrTotal)
    {
        return toAjax(scrTotalService.insertScrTotal(scrTotal));
    }

    /**
     * 修改【请填写功能名称】
     */

    @PutMapping
    public AjaxResult edit(@RequestBody ScrTotal scrTotal)
    {
        System.out.println("ooooooooooooooooooooooooooooooooooooooo");
        System.out.println(scrTotal);
        try{
            return toAjax(scrTotalService.updateScrTotal(scrTotal));

        }
        catch(Exception e){
            System.out.println(e);
            return AjaxResult.success();
        }
    }

    @PutMapping("/user")
    public AjaxResult edituser(@RequestBody UserInfo userInfo)
    {
        return toAjax(userInfoService.updateUserInfo(userInfo));
    }

    /**
     * 删除【请填写功能名称】
     */

    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(scrTotalService.deleteScrTotalByIds(ids));
    }



    @GetMapping("/download")
    public ResponseEntity<InputStreamResource> downloadFile(@RequestParam Integer id, @RequestParam String type) throws IOException {
        String dir="";
        String filename = id+"."+type;
        dir = Constants.BASE_DIR+id;
        Path filePath = Paths.get(dir,filename);
        File file = filePath.toFile();
        InputStreamResource resource = new InputStreamResource(new FileInputStream(file));
        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + filename);

        return ResponseEntity.ok()
                .headers(headers)
                .contentLength(file.length())
                .contentType(MediaType.parseMediaType("application/octet-stream"))
                .body(resource);
    }

}
